// 云函数入口文件
const COS = require('cos-nodejs-sdk-v5')
var STS = require('sts');
exports.main = async(event, context) => {
  return new Promise(async(resolve, reject) => {
    var config = {
      secretId: '',
      secretKey: '',
      proxy: '',
      durationSeconds: 1800,
      bucket: '',
      region: 'ap-shanghai',
      allowPrefix: '*',
      allowActions: [
        // 简单上传
        'name/cos:PutObject',
        'name/cos:PostObject',
        // 分片上传
        'name/cos:InitiateMultipartUpload',
        'name/cos:ListMultipartUploads',
        'name/cos:ListParts',
        'name/cos:UploadPart',
        'name/cos:CompleteMultipartUpload'
      ],
    };
    var shortBucketName = config.bucket.substr(0, config.bucket.lastIndexOf('-'));
    var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
    var policy = {
      'version': '2.0',
      'statement': [{
        'action': config.allowActions,
        'effect': 'allow',
        'principal': {
          'qcs': ['*']
        },
        'resource': [
          'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
        ],
      }],
    };
    STS.getCredential({
      secretId: config.secretId,
      secretKey: config.secretKey,
      proxy: config.proxy,
      durationSeconds: config.durationSeconds,
      policy: policy,
    }, function(err, tempKeys) {
      var result = JSON.stringify(err || tempKeys) || '';
      resolve({
        data: result,
      })
    });
  })

}